package com.atguigu.smsservice.controller;

import com.atguigu.commonutils.RandomUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.result.RedisKey;
import com.atguigu.commonutils.ResponseEnum;
import com.atguigu.servicebase.exception.Assert;
import com.atguigu.smsservice.service.SmsService;
import com.atguigu.smsservice.utils.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @descriptions:
 * @author: pandengZhu
 * @date: 2024/4/9 11:47
 * @version: 1.0
 */

@Slf4j
//@CrossOrigin
@Api(tags = "短信管理")
@RestController
@RequestMapping("/edusms/sms")
public class SmsController {

    @Resource
    private SmsService smsService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public R code(@ApiParam(value = "手机号", required = true)
                  @PathVariable String phone) {

        //1.判断手机号是否注册
/*        boolean result = smsService.checkMobile(phone);
        System.out.println("result=================" + result);
        Assert.isTrue(result == true, ResponseEnum.LOGIN_AUTH_ERROR);*/

        //2.判断手机号不能为空
        Assert.notEmpty(phone, ResponseEnum.MOBILE_NULL_ERROR);
        //3.判断手机号是否正确
        Assert.notEmpty(phone, ResponseEnum.MOBILE_ERROR);
        //4.生成验证码
        String smsCode = RandomUtils.getSixBitRandom();
        log.info("短信验证码===========================" + smsCode);
        //5.组装短信参数模板
        Map<String, Object> param = new HashMap<>();
        param.put("smsCode", smsCode);
        //6.发送短信
        smsService.sendSmsCode(phone, SmsProperties.TEMPLATE_CODE, param, smsCode);
        //7.验证码存入redis
        stringRedisTemplate.opsForValue().set(RedisKey.GULI_SMS_CODE + phone, smsCode, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }

/*    @GetMapping("/checkPhone/{phone}")
    public R checkPhone(@ApiParam(value = "手机号",required = true)
                        @PathVariable String phone) {
        boolean result = userInfoClient.checkMobile(phone);
        return null;
    }*/
}
